import random
from datetime import datetime

import redis
import requests
import time
from faker import Faker

fake = Faker()

count = 1
redis_conn = redis.Redis(host='124.220.186.165', password='ilcjals', port=6379)
# API地址和基本信息
# base_url = 'http://124.223.139.46:30001/api'
base_url = 'http://152.32.143.7:8080/api'

timeout = 7 * 60 * 60
# 初始化 random_phone 变量
phone = None

with open('error_old.txt', 'w', encoding='utf-8') as error_file:

    start_time = time.time()
    while time.time() - start_time < timeout:
        try:
            # 生成一个随机的名字
            first_name = fake.first_name()
            last_name = fake.last_name()
            random_phone = redis_conn.randomkey()
            random_access_token = redis_conn.get(random_phone).decode('utf-8')
            headers = {
                "Authorization": f"Bearer {random_access_token}",
            }
            data = {
                "first_name": first_name,
                "last_name": last_name,
                "country": "Nigeria",
            }
            response = requests.post(f"{base_url}/user/profile", headers=headers, data=data)
            if response.status_code != 200:
                error_message = f"第{count}条数据{random_phone}，用户信息修改失败，状态码{response.status_code}，响应信息{response.text},token{random_access_token}"
                error_file.write(error_message + '\n')
                error_file.flush()
            print(f"第{count}条数据{random_phone}执行完成")
            count += 1
            time.sleep(5)
        except Exception as e:
            print(f"异常时间{datetime.now()}")
            error_file.write(f'第{count}条数据，电话号码{random_phone}，出现异常：{e}\n')
            count += 1
